import request from "@/axios/request";

const {ElMessage} = require("element-plus");

export default {
    name: "CommentManagement",
    data() {
        return {
            search: "",
            currentPage: 1,
            pageSize: 10,
            total: 0,
            allData: [],       // 存储全量数据
            tableData: [],     // 当前页数据
            isAllSelected: false, // 是否全选
            selectedComments: []  // 当前页已选中的 commentId 列表
        };
    },
    computed: {
        paginatedData() {
            const start = (this.currentPage - 1) * this.pageSize;
            const end = start + this.pageSize;
            return this.allData.slice(start, end);
        }
    },
    created() {
        this.load();
        this.loading = true;
        setTimeout(() => {
            this.loading = false;
        }, 1000);
    },
    methods: {
        async load() {
            try{
                const res = await request.get("/comment/findAll");
                if (res.code === 200) {
                    this.allData = res.data || [];
                    this.total = this.allData.length;
                    this.tableData = this.paginatedData;
                } else {
                    ElMessage.error(res.msg || "加载失败");
                    this.allData = [];
                    this.tableData = [];
                    this.total = 0;
                }
                this.loading = false;
            } catch (err){
                console.error(err);
                ElMessage.error("网络错误，请稍后再试");
                this.allData = [];
                this.tableData = [];
                this.total = 0; 
                this.loading = false;
            }
        },
        async filterData() {
            const res = await request.get("/comment/findAll");
            if (res.code === 200) {
                this.allData = res.data || [];
                this.total = this.allData.length;
                this.tableData = this.paginatedData;
            } 

            let data = this.allData;
            if (this.search) {
                const id = parseInt(this.search);
                data = data.filter(item => item.tenantId === id);
            }
            this.allData = data;
            this.total = data.length;
            this.tableData = this.paginatedData;
        },
        reset() {
            this.search = "";
            this.currentPage = 1;
            this.load();
        },
        async handleDelete(commentId) {
            //删除
            request.delete(`/comment/delete/${commentId}`).then((res) => {
                if (res.code === 200) {
                    ElMessage({
                        message: "删除成功",
                        type: "success",
                    });
                    this.load();
                } else {
                    ElMessage({
                        message: res.msg,
                        type: "error",
                    });
                }
            });
        },
        handleSizeChange(pageSize) {
            this.pageSize = pageSize;
            this.tableData = this.paginatedData;
        },
        handleCurrentChange(pageNum) {
            this.currentPage = pageNum;
            this.tableData = this.paginatedData;
        },
        toggleSelectAll(checked) {
            if (checked) {
                this.selectedComments = this.tableData.map(item => item.commentId);
            } else {
                this.selectedComments = [];
            }
        },
        // 确认批量删除
        batchDeleteConfirm() {
            if (this.selectedComments.length === 0) {
                ElMessage.warning("请至少选择一条评论");
                return;
            }

            this.$confirm('确定删除当前页所有评论吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.batchDelete();
            }).catch(() => {
                this.$message.info('已取消删除');
            });
        },
        // 批量删除数据
        async batchDelete() {
            if (!this.selectedComments.length) {
                ElMessage.warning("没有可删除的数据");
                return;
            }

            try {
                // 并行删除所有选中的评论
                const deletePromises = this.selectedComments.map(commentId => {
                    return request.delete(`/comment/delete/${commentId}`);
                });

                const results = await Promise.all(deletePromises);

                // 检查是否有失败的请求
                const failed = results.some(res => res.code !== "200");

                if (!failed) {
                    ElMessage.success("批量删除成功");
                } else {
                    ElMessage.warning("部分评论删除失败");
                }

                // 刷新数据
                this.selectedComments = [];
                this.isAllSelected = false;
                this.load();

            } catch (err) {
                console.error(err);
                ElMessage.error("网络错误，请稍后再试");
            }
        }
    },
};